<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/11
 * Time: 17:00
 */
namespace app\api\home;

class Auth extends Common
{
    const appid = 'wxe9e23354104fc7b1';
    const secret = '7ba941a091510825168b54c9081481d8';
    const wxUrl = 'https://api.weixin.qq.com';
    const login = '/sns/jscode2session';

    public function login_by_weixin()
    {
        $params = input('post.',[]);
        if(!$params){
            return _json(-1, '参数缺失');
        }
        $openRes = self::getOpenId($params['code']);
        if(isset($openRes['errcode']) && $openRes['errcode'] != 0){
            return _json(-1, '获取信息错误'.$openRes['errcode']);
        }

        $user = db('user')->where('openid',$openRes['openid'])->find();
        if($user){
            //更新用户信息
            $data = [
                'nickname'=>$params['nickName'],
                'avatarUrl'=>$params['avatarUrl']
            ];
            $user_id = $user['user_id'];
            db('user')->where('user_id',$user_id)->update($data);

        }else{
            // 注册
            $data = [
                'nickname' => $params['nickName'],
                'openid' => $openRes['openid'],
                'avatarUrl'=> $params['avatarUrl'],
                'country'=> $params['country'],
                'province'=> $params['province'],
                'city'=> $params['city'],
                'gender'=> $params['gender'],
            ];
            $user_id = db('user')->insertGetId($data);
        }
        if($user_id){
            $data = [
                'user_id' =>$user_id,
                'token' => '123456'
            ];
            return _json(0, '登录成功',$data);
        }
    }

    private static function getOpenId($code)
    {
        $url = self::wxUrl.self::login.'?appid='.self::appid.'&secret='.self::secret.'&js_code='.$code.'&grant_type=authorization_code';
        $res = self::httpGet($url);
        return $res;
    }

    private static function httpGet($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res,true);
        return $res;
    }
}